package com.wwm.petadopt;


import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bmob.pay.tool.BmobPay;
import com.bmob.pay.tool.PayListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.Holder;
import com.orhanobut.dialogplus.OnCancelListener;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.bmob.v3.Bmob;


public class PetDetailActivity extends Activity {
    EditText priceEDT;
    TextView name;
    TextView variety;
    TextView age;
    TextView info;
    ImageView img;
    TextView  sex;
    TextView phone;
    TextView addr;
    TextView agency;
    private RequestQueue mRequestQueue;
    PetDetail petDetail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bmob.initialize(this, "af01e2fbdf7674a51ee0624c3dfcc586");
        ActionBar ab = getActionBar();
        if (ab != null) {
            View actionbarview = getLayoutInflater().inflate(R.layout.actionbar, null);
            ((TextView) actionbarview.findViewById(R.id.text_actionbar)).setText(R.string.detail);

            ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            ab.setCustomView(actionbarview);

        }
        setContentView(R.layout.activity_pet_detail);

        img = (ImageView)findViewById(R.id.image_detail);
        name = (TextView)findViewById(R.id.text_name);
        age  = (TextView)findViewById(R.id.text_age);
        variety = (TextView)findViewById(R.id.text_variety);
        agency=(TextView)findViewById(R.id.text_addoptionAgency);
        sex=(TextView)findViewById(R.id.text_petSex);
        phone=(TextView)findViewById(R.id.text_adoptionPhone);
        addr=(TextView)findViewById(R.id.text_adoptionAddr);


        info = (TextView)findViewById(R.id.text_petdetail);
        Intent intent=getIntent();
        final String petId=intent.getStringExtra("petId");
        mRequestQueue = Volley.newRequestQueue(this);
        Map<String, String> map = new HashMap<String, String>();

        map.put("Request_pet_id", petId);

        JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_PET_INFO_URL, new JSONObject(map), new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
                Log.i("petadopt", response.toString());
                try{
                     petDetail = new PetDetail(response);
                    name.setText(petDetail.petName);
                    age.setText("年龄："+petDetail.petAge+"岁");
                    info.setText("简介：\n"+petDetail.introduce);
                    variety.setText("品种："+petDetail.petVariety);

                    agency.setText("领养机构："+petDetail.adoptionAgency);
                    sex.setText("性别："+petDetail.petSex);
                    phone.setText("领养电话："+petDetail.phoneNum);
                    addr.setText("领养地址："+petDetail.adoptionAddress);

                    DisplayImageOptions options = new DisplayImageOptions.Builder()
                            .displayer(new RoundedBitmapDisplayer(30)) //rounded corner bitmap
                            .cacheInMemory(true)
                            .cacheOnDisc(true)
                            .build();

                    ImageLoader imageLoader = ImageLoader.getInstance();
                    imageLoader.displayImage(petDetail.imageUrl, img, options);

                }catch (Exception e)
                {}

            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Log.i("petadopt", error.getMessage());
            }
        });
        mRequestQueue.add(jr);

        Button btn_OneKeyAdoption = (Button) findViewById(R.id.button_one_key_adoption);
        btn_OneKeyAdoption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GlobalData.isLogin == true) {
                    showDialog(0, DialogPlus.Gravity.CENTER, false, false);
                } else {
                    Toast.makeText(PetDetailActivity.this, "请登录", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent("android.intent.action.LOGIN");
                    startActivity(intent);

                }

            }
        });

    }

    private void showDialog(int holderId, DialogPlus.Gravity gravity, boolean showHeader, boolean showFooter) {
        Holder holder;
        holder = new ViewHolder(R.layout.dialog_price);

        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogPlus dialog, View view) {
                switch (view.getId()) {
                    case R.id.button_price_confirm:

                    new BmobPay(PetDetailActivity.this).pay(Float.parseFloat(priceEDT.getText().toString()), "捐款", new PayListener() {

                        String book_id;

                        @Override
                        public void succeed() {
                            Log.i("petadopt", "succeed!!!!");
                            mRequestQueue = Volley.newRequestQueue(PetDetailActivity.this);
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("book_id", book_id);
                            map.put("pet_id", petDetail.petId);
                            map.put("user_name", GlobalData.username);

                            JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.UPLOAD_ORDER_INFO_URL, new JSONObject(map), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    try
                                    {
                                        Log.i("petadopt", response.toString());
                                        int retValue = response.getInt("success");
                                        if (retValue == 0)
                                        {
                                            Toast.makeText(PetDetailActivity.this, "捐款成功", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                    catch(JSONException e)
                                    {

                                    }

                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.i("petadopt", error.getMessage());
                                }
                            });
                            mRequestQueue.add(jr);
                        }

                        @Override
                        public void fail(int code, String reason) {
                            Log.i("petadopt", "failed " + code + " " + reason);

                            mRequestQueue = Volley.newRequestQueue(PetDetailActivity.this);
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("book_id", book_id);
                            map.put("pet_id", petDetail.petId);
                            map.put("user_name", GlobalData.username);

                            JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.UPLOAD_ORDER_INFO_URL, new JSONObject(map), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    try
                                    {
                                        Log.i("petadopt", response.toString());
                                        int retValue = response.getInt("success");
                                        if (retValue == 0)
                                        {
                                            Toast.makeText(PetDetailActivity.this, "捐款成功", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                    catch(JSONException e)
                                    {

                                    }

                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.i("petadopt", error.getMessage());
                                }
                            });
                            mRequestQueue.add(jr);
                        }

                        @Override
                        public void unknow() {
                            Log.i("petadopt", "unknow");
                        }

                        @Override
                        public void orderId(String orderId) {
                            Log.i("petadopt", "orderId " + orderId);
                            book_id = orderId;
                        }
                    });
                    PetDetailActivity.this.finish();
                    break;
                    case R.id.button_price_cancel:

                        break;
                }
                dialog.dismiss();
            }
        };

        OnDismissListener dismissListener = new OnDismissListener() {
            @Override
            public void onDismiss(DialogPlus dialog) {

            }
        };

        OnCancelListener cancelListener = new OnCancelListener() {
            @Override
            public void onCancel(DialogPlus dialog) {

            }
        };


        final DialogPlus dialog = new DialogPlus.Builder(this)
                .setContentHolder(holder)
                .setCancelable(true)
                .setGravity(gravity)
                .setOnClickListener(clickListener)
                .setOnDismissListener(dismissListener)
                .setOnCancelListener(cancelListener)
                .create();
        priceEDT = (EditText) dialog.getHolderView().findViewById(R.id.edittext_price);
        dialog.show();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_pet_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
